var app=getApp();

Component({
  externalClasses: ['wr-class'],

  properties: {
    goodsList: {
      type: Array,
      value: [],
      observer: function(){
      }
    },
    globalData: {
      type: Object,
      value: null,
      observer: function(){
        this.setData({
          globalData: app.data.globalData
        })
        console.log('goods-list组件 Observe中', this.properties.globalData)
      }
    },
    id: {
      type: String,
      value: '',
      observer: (id) => {
        this.genIndependentID(id);
      },
    },
    thresholds: {
      type: Array,
      value: [],
    }
  },

  data: {
    independentID: '',
  },

  observers:{
    'globalData.order.goods': function(e){
      console.log('订单发生变化，传入参数为：', e)
    }
  },

  lifetimes: {
    ready() {
      this.init();
    },
  },

  pageLifetimes:{
    show(){ 
      // this.setData({
      //   globalData: app.data.globalData
      // })
    },
  },

  methods: {
    onClickGoods(e) {
      const { index } = e.currentTarget.dataset;
      this.triggerEvent('click', { ...e.detail, index });
    },

    onAddCart(e) {
      const { index } = e.currentTarget.dataset;
      this.triggerEvent('addcart', { ...e.detail, index });
    },

    refreshCart(e){
      // 1. 修改全局数据
      const { index } = e.currentTarget.dataset;
      const key = `globalData.allGoodsList[${index}].count`; // 动态构造路径
      this.setData({
        [key]: e.detail.quantity,
      })
      // 2. 添加到unpaylist
      let goodsList = this.data.globalData.allGoodsList;
      let unpayOrderList = this.data.globalData.order.unpay.goods;
      let find = false;
      for(let i in unpayOrderList){
        if(unpayOrderList[i].id === goodsList[index].id){
          find = true;
          if(goodsList[index].count === 0){
            unpayOrderList.splice(i, 1);
          }else{
            unpayOrderList[i].count = goodsList[index].count;
          }
          break;
        }
      }
      if(!find && goodsList[index].count !== 0){
        unpayOrderList.push(JSON.parse(JSON.stringify(goodsList[index])));
      }
      console.log('refreshCart，全局数据globalData: ', app.data.globalData)
    },

    onClickGoodsThumb(e) {
      const { index } = e.currentTarget.dataset;
      this.triggerEvent('thumb', { ...e.detail, index });
    },

    init() {
      this.genIndependentID(this.id || '');
    },

    genIndependentID(id) {
      if (id) {
        this.setData({ independentID: id });
      } else {
        this.setData({
          independentID: `goods-list-${~~(Math.random() * 10 ** 8)}`,
        });
      }
    },
  },
});
